package com.redpack.redpost.struts.form;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import com.redpack.redpost.util.to.UserLogin;

public class accessForm extends ActionForm {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private String usr;
    private String pass;
    
	public String getUsr() {
		return usr;
	}
	public void setUsr(String usr) {
		this.usr = usr;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}	
    
	public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
		
		ActionErrors errors = new ActionErrors( );
		HttpSession session = request.getSession( ) ;
		String idioma = "";
		
	
		if (session.getAttribute("idioma") != null && session.getAttribute("idioma") != ""){
			idioma = session.getAttribute("idioma").toString();
	
		}
		
		if ( usr == null || usr.trim().length() == 0 ) {
            errors.add("NombreVacio", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.usr"+idioma));
        }else
            if ( pass == null || pass.trim( ).length( ) == 0 ) {
                errors.add("PassVacio", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.pwd"+idioma));
            }
		
		//revisa si hay errores
        if ( errors.size() > 0 )
        	return errors ;
        
        try {
        	
        	UserLogin userLogin = new UserLogin(usr, pass) ;
        	
        	// revisa si coinciden las contrasenias
        	boolean res = userLogin.login( ) ;
        	
        	// en caso de falso
        	if (!res) {
        		errors.add("UserPassIncorrect", new ActionMessage("com.redpack.redpost.web.errors.modules.acceso.no"+idioma));
        		request.setAttribute("errorLogin", "si");
        	} else {
        		/*
        		 * 
        		 * */
        		request.getSession().setAttribute("UserLogin", userLogin);
        	}
        		
        	
        } catch (Exception e) {
			e.printStackTrace();
		}
        
        request.setAttribute("error", "1");
		return errors ;
		
	}

}
